from datetime import datetime
import talib
import pandas as pd
from vnpy.trader.ui import create_qapp, QtCore
from vnpy.trader.constant import Exchange, Interval
from vnpy.trader.database import database_manager
from vnpy.chart import ChartWidget, VolumeItem, CandleItem
import os
import importlib
import traceback
from datetime import datetime
from threading import Thread
from pathlib import Path
from inspect import getfile

from vnpy.event import Event, EventEngine
from vnpy.trader.engine import BaseEngine, MainEngine
from vnpy.trader.constant import Interval
from vnpy.trader.utility import extract_vt_symbol
from vnpy.trader.object import (
    HistoryRequest,
    LogData
)
from vnpy.trader.rqdata import rqdata_client
from vnpy.trader.database import database_manager
from vnpy.app.cta_strategy import CtaTemplate
from vnpy.app.cta_strategy.backtesting import (
    BacktestingEngine, OptimizationSetting, BacktestingMode
)
import time


if __name__ == "__main__":
    app = create_qapp()
    symbol = "IF2201"
    exchange = Exchange.CFFEX
    start=datetime(2021, 12, 1)
    end=datetime(2022, 3, 17)
    interval=Interval.MINUTE
    bars = database_manager.load_bar_data(
        symbol,
        Exchange.CFFEX,
        interval=Interval.MINUTE,
        start=start,
        end=end
    )
    if not bars or len(bars) == 0:

        req = HistoryRequest(
            symbol=symbol,
            exchange=exchange,
            interval=Interval.MINUTE,
            start=start,
            end=end
        )

        try:
            bars = rqdata_client.query_history(req)

            if bars:
                database_manager.save_bar_data(bars)
                print(f"{symbol}-{interval}历史数据下载完成")
            else:
                print(f"数据下载失败，无法获取{symbol}的历史数据")
        except Exception:
            msg = f"数据下载失败，触发异常：\n{traceback.format_exc()}"
            print(msg)

    widget = ChartWidget()
    widget.add_plot("candle", hide_x_axis=True)
    # widget.add_plot("candle2", hide_x_axis=False)
    widget.add_plot("volume", maximum_height=200)
    widget.add_item(CandleItem, "candle", "candle")
    # widget.add_item(CandleItem, "candle2", "candle2")
    widget.add_item(VolumeItem, "volume", "volume")
    widget.add_cursor()

    n = 1000
    history = bars[:n]
    new_data = bars[n:]

    widget.update_history(history)

    def update_bar():
        bar = new_data.pop(0)
        widget.update_bar(bar)
    # import pandas as pd
    # df = pd.DataFrame(bars, columns=['datetime','open_price', 'high_price', 'low_price','close_price']) 
    # print(type(bars))
    # result = talib.EMA(df.close_price, 20)
    # print( result.head(3))
    timer = QtCore.QTimer()

    timer.timeout.connect(update_bar)
    timer.start(1000)

    widget.show()
    app.exec_()
